package com.jietuo.class02;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2024/3/1
 * @description: 4，数组（固定长度大小）实现栈和队列（环形数组）
 */
public class Code04_ArrayToStackAndQueue {

    // 环形数组
    public static class RingArray {
        private int curSize;
        private int firstIndex;
        private int lastIndex;
        private int[] arr;

        public RingArray(int size) {
            arr = new int[size];
            firstIndex = 0;
            lastIndex = 0;
            curSize = 0;
        }

        public int length() {
            return arr.length;
        }

        public void push(int value) {
            if (curSize == length()) {
                // 数组已满
                throw new RuntimeException("栈满了，不能再加了");
            }
            arr[firstIndex] = value;
            curSize++;
            firstIndex = nextIndex(firstIndex);
        }

        public int pop() {
            if (curSize == 0) {
                throw new RuntimeException("栈空了，不能再拿了");
            }
            int result = arr[lastIndex];
            curSize--;
            lastIndex = nextIndex(lastIndex);
            return result;
        }

        private int nextIndex(int i) {
            if (i < length() - 1) {
                return i++;
            } else {
                return 0;
            }
        }

    }
}
